import requests
import re


#
# # 1. 先发起get请求 获取隐藏域csrfmiddlewaretoken  和 cookie
# login_url = "http://127.0.0.1:8000/admin/login/?next=/admin/login"
# response_login = requests.get(login_url)
# print(response_login.cookies)
# csrfmiddlewaretoken = re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="(.*?)">', response_login.text).group(1)
# print(csrfmiddlewaretoken)
#
#
#
# # 2. 发起post请求  携带隐藏域  用户名  密码
# response_login = requests.post(login_url, data={
#     'csrfmiddlewaretoken': csrfmiddlewaretoken,
#     'username': 'admin',
#     'password': '123456'
# }, cookies=response_login.cookies)
# print(response_login.text)



# 使用会话  自动携带 请求的所有的cookie信息

login_url = "http://127.0.0.1:8000/admin/login/?next=/admin/login"
session = requests.Session()
print(session.cookies)
response = session.get(login_url)
print(session.cookies)
csrfmiddlewaretoken = re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="(.*?)">', response.text).group(1)
print(csrfmiddlewaretoken)

response = session.post(login_url, data={
    'username': 'admin',
    'password': '123456',
    'csrfmiddlewaretoken': csrfmiddlewaretoken
})
print(response.text)
